package com.st.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * @version V 1.0
 * @auther ROG
 * @date 2024/10/25
 * @project_name back
 * @description
 */
@Component
public class WxLoginUtils {

    @Value("${wechat.app-id}")
    private String appId;

    @Value("${wechat.app-secret}")
    private String appSecret;
    private final String WECHAT_API_URL = "https://api.weixin.qq.com/sns/jscode2session";

    public Map<String, Object> getSessionInfo(String code) {
        RestTemplate restTemplate = new RestTemplate();
        String url = WECHAT_API_URL + "?appid=" + appId + "&secret=" + appSecret + "&js_code=" + code + "&grant_type=authorization_code";

        String responseStr = restTemplate.getForObject(url, String.class);

        // Map<String, String> response = restTemplate.getForObject(url, Map.class);
        // 使用 ObjectMapper 手动解析为 Map
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, Object> responseMap = null;
        try {
            responseMap = objectMapper.readValue(responseStr, new TypeReference<Map<String, Object>>() {});
        } catch (JsonProcessingException e) {
            throw new RuntimeException("解析微信登录响应失败", e);
        }
        return responseMap;
    }
}
